package com.jds.test.websocket;

import com.jds.test.http.BodyToResponseEncoder;
import com.jds.test.http.HttpServerHandler;
import com.jds.test.http.RequestToBodyDecoder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * Initializer
 *
 * @author shane
 */
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    public void initChannel(SocketChannel ch) throws Exception {

        ChannelPipeline pipeline = ch.pipeline();

        // http 编解码
        pipeline.addLast(new HttpServerCodec());

        // 大对象出站
     //   pipeline.addLast(new ChunkedWriteHandler());

        // 捕捉出站异常
        pipeline.addLast(new OutBoundExceptionHandler());

        // 聚合
        pipeline.addLast(new HttpObjectAggregator(64 * 1024));

        // 初始http
        pipeline.addLast(new HttpRequestHandler());

        // netty 代理 握手，处理 close ping pong
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));

        // string -> websocketframe
        pipeline.addLast(new WebSocketFrameEncoder());

        // websocketframe -> string
        pipeline.addLast(new WebSocketFrameDecoder());

        // 读空闲9秒激发
        ch.pipeline().addLast(new IdleStateHandler(9, 0, 0, TimeUnit.SECONDS));

        // 自定义 websocket 处理
        pipeline.addLast(new TextWebSocketFrameHandler());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        super.exceptionCaught(ctx, cause);
    }
}
